package com.changgou.order.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 请求拦截器（添加令牌到请求头中）
 * @author zhengjd
 * @date 2020/5/17 23:57
 */
@Component
public class MyFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            //获取请求的相关变量
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null){
                //取出request
                HttpServletRequest request = requestAttributes.getRequest();
                //获取所有头文件的信息
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames !=null){
                    while (headerNames.hasMoreElements()){
                        //头文件的key
                        String header = headerNames.nextElement();
                        //头文件的value
                        String values = request.getHeader(header);
                        //将令牌数据添加到头文件中
                        requestTemplate.header(header,values);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
